package com.gdougms.controller;

import com.gdougms.entity.User;
import com.gdougms.service.UserService;
import com.gdougms.entity.HttpMessage;
import com.gdougms.tools.RandomCode;
import com.gdougms.tools.RedisCodeGetSet;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;
@Slf4j
@RestController
@Api(value = "体育馆管理系统用户接口" ,tags = {"体育馆管理系统用户接口"})
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    ObjectFactory<HttpMessage> httpMessageObjectFactory;

    @Autowired
    HttpSession httpSession;

    @Autowired
    RedisCodeGetSet redisCodeGetSet;

    @ApiOperation(value="根据身份证号或者学号查询用户信息", notes="如果不存在，result为false，只有管理员或者用户自己才能查询到用户信息")
    @GetMapping("/getUser")
    public HttpMessage getUserByNumberOrIDCard(@RequestParam String id){
        HttpMessage httpMessage = httpMessageObjectFactory.getObject();
        System.out.println(id);
        User user = userService.getUserByNumberOrIDCard(id);
        if (user == null){
            httpMessage.setCode(-1);
            httpMessage.setMessage("没有这个用户");
            httpMessage.setResult(false);
        }else {
            httpMessage.setCode(200);
            httpMessage.setMessage("存在这个用户");
            httpMessage.setResult(true);
            httpMessage.setObject(user);
        }
        return httpMessage;
    }

    @ApiOperation(value="根据身份证号或者学号查询是否存在用户", notes="如果不存在，result为false，否则为true，用在登录时判断账号是否存在,不限制使用")
    @GetMapping("/getIfUser")
    public HttpMessage getIfUserByNumberOrIDCard(@RequestParam String id){
        HttpMessage httpMessage = httpMessageObjectFactory.getObject();
        System.out.println(id);
        User user = userService.getUserByNumberOrIDCard(id);
        if (user == null){
            httpMessage.setCode(-1);
            httpMessage.setMessage("没有这个用户");
            httpMessage.setResult(false);
        }else {
            httpMessage.setCode(200);
            httpMessage.setMessage("存在这个用户");
            httpMessage.setResult(true);
        }
        return httpMessage;
    }


    @ApiOperation(value="获取所有用户", notes="普通用户不具备该权限")
    @GetMapping("/getUsers")
    public List<User> getUsers(){
        return userService.getUsers();
    }

    @ApiOperation(value="登录", notes="参数名为username password，如果账号密码不存在，result中为-1，密码已经经过md5加密")
    @ApiParam(value = "password",defaultValue = "123456789")
    @PostMapping("/login")
    public HttpMessage login(@RequestParam String username,
                             @RequestParam String password){
        HttpMessage httpMessage = httpMessageObjectFactory.getObject();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        User user = userService.login(username,password);
        if(user == null){
            httpMessage.setCode(-1);
            httpMessage.setMessage("登录失败,请检查账号密码");
            httpMessage.setResult(false);
        }else{
            httpSession.setAttribute("User",user);
            httpMessage.setCode(200);
            httpMessage.setMessage("登录成功");
            httpMessage.setResult(true);
            httpMessage.setObject(user);
        }
        return httpMessage;
    }


    @ApiOperation(value="游客注册", notes="身份证号+密码+邮箱+姓名+用户输入的验证码")
    @PostMapping("/register")
    public HttpMessage register(@RequestParam String idCard,
                                @RequestParam String password,
                                @RequestParam String email,
                                @RequestParam String name,
                                @RequestParam String code){
        User user = userService.getUserByNumberOrIDCard(idCard);
        HttpMessage httpMessage = httpMessageObjectFactory.getObject();

        //存在该用户
        if(user != null){
            httpMessage.setCode(-1);
            httpMessage.setMessage("用户已经存在");
            httpMessage.setResult(false);
            return httpMessage;
        }

        password = DigestUtils.md5DigestAsHex(password.getBytes());
        int result = 0;

        HttpMessage message = redisCodeGetSet.readCode(email, code);
        if(message.getResult()){
            result = userService.register(name,idCard,password,email);
        }else{
            httpMessage.setCode(-1);
            httpMessage.setMessage(message.getMessage());
            httpMessage.setResult(false);
            return httpMessage;
        }

        if(result == 0){
            httpMessage.setCode(-1);
            httpMessage.setMessage("系统异常，用户注册失败");
            httpMessage.setResult(false);
        }else{
            httpMessage.setCode(200);
            httpMessage.setMessage("注册成功");
            httpMessage.setResult(true);
        }
        return httpMessage;
    }

    @ApiOperation(value="忘记密码/更改密码", notes="忘记密码填写邮箱之后发送验证码，然后填写信息提交表单")
    @PostMapping("/emailVerification")
    public HttpMessage emailVerification(@RequestParam String email,
                                  @RequestParam String code,
                                  @RequestParam String username,
                                  @RequestParam String password){
        int result = 0;
        HttpMessage httpMessage = httpMessageObjectFactory.getObject();
        //密码加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //验证是否一致
        HttpMessage message = redisCodeGetSet.readCode(email, code);
        //一致
        if(message.getResult()){
            result = userService.updatePassword(password,username);
        }else {
            httpMessage.setCode(-1);
            httpMessage.setMessage(message.getMessage());
            httpMessage.setResult(false);
            return httpMessage;
        }
        if (result != 0) {
            httpMessage.setCode(200);
            httpMessage.setMessage("更改成功");
            httpMessage.setResult(true);
        }else {
            httpMessage.setCode(-1);
            httpMessage.setMessage("系统异常，更新失败");
            httpMessage.setResult(false);
        }
        return httpMessage;
    }

    @ApiOperation(value="第一次修改密码绑定邮箱接口", notes="邮箱，点击发送验证码，填写验证码")
    @PostMapping("/emailVerificationBind")
    public HttpMessage emailVerificationBind(@RequestParam String email,
                                             @RequestParam String code){

        //获取当前登录用户以及初始化message类
        HttpMessage httpMessage = httpMessageObjectFactory.getObject();
        User user = (User) httpSession.getAttribute("User");

        //获取查询redis中的验证码与用户填写是否一致
        HttpMessage message = redisCodeGetSet.readCode(email,code);
        int result = 0;
        //是否验证码正确以及更新成功
        if (message.getResult()){
            result = userService.bindEmail(email,user.getNumber());
            if(result != 0){
                httpMessage.setMessage("绑定邮箱成功！");
                httpMessage.setCode(200);
                httpMessage.setResult(true);
            }else {
                httpMessage.setMessage(message.getMessage());
                httpMessage.setCode(-1);
                httpMessage.setResult(false);
            }
        }
        return httpMessage;
    }

    @ApiOperation(value="管理员获取普通用户（老师 + 学生 + 游客）", notes="不包括管理员自己")
    @GetMapping("/userList")
    public HttpMessage getUserList(){
        HttpMessage httpMessage = httpMessageObjectFactory.getObject();
        //添加到http message
        List<User> list = userService.getUserList();
        httpMessage.setObject(list);
        if(list != null){
            httpMessage.setResult(true);
            httpMessage.setCode(200);
        }else {
            httpMessage.setResult(false);
            httpMessage.setCode(-1);
        }
        return httpMessage;
    }

    @ApiOperation(value="管理员删除用户", notes="根据username（number或者idcard其中之一，符合其一就删除）")
    @PostMapping("/deleteUser")
    public HttpMessage deleteUser(@RequestParam String username){
        HttpMessage httpMessage = httpMessageObjectFactory.getObject();

        int result = userService.deleteUser(username);
        if (result != 0){
            httpMessage.setResult(true);
            httpMessage.setCode(200);
            httpMessage.setMessage("删除成功！");
        }else {
            httpMessage.setResult(false);
            httpMessage.setCode(-1);
            httpMessage.setMessage("系统异常，删除失败！");
        }
        return httpMessage;
    }


    /**@Title
     * @Description 增加用户需判断用户是否有number
     * @Param [number, idCard, name, role]
     * @return com.gdougms.entity.HttpMessage
     * @Author iceF
     * @Date 2021/6/21
    */
    @ApiOperation(value="管理员增加用户", notes="同注册差不多,增加的是普通用户（学生+游客+教师）")
    @PostMapping("/addUser")
    public HttpMessage addUser(@RequestParam(required = false) String number,
                               @RequestParam String idCard,
                               @RequestParam String name,
                               @RequestParam(required = false) String email,
                               @RequestParam int role){

        HttpMessage httpMessage = httpMessageObjectFactory.getObject();
        //判断用户是否存在
        if(number != null){
            User user = userService.getUserByNumberOrIDCard(number);

            //存在该用户
            if(user != null){
                httpMessage.setCode(-1);
                httpMessage.setMessage("用户已经存在，添加失败！");
                httpMessage.setResult(false);
                return httpMessage;
            }
        }
        User user = userService.getUserByNumberOrIDCard(idCard);
        //存在该用户
        if(user != null){
            httpMessage.setCode(-1);
            httpMessage.setMessage("用户已经存在，添加失败！");
            httpMessage.setResult(false);
            return httpMessage;
        }

        //不存在
        String password = idCard.substring(idCard.length()-6);
        //密码加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        int result = userService.addUser(name,number,idCard,password,role,email);
        if (result != 0){
            httpMessage.setResult(true);
            httpMessage.setCode(200);
            httpMessage.setMessage("添加成功！");
        }else {
            httpMessage.setResult(false);
            httpMessage.setCode(-1);
            httpMessage.setMessage("系统异常，添加失败！");
        }
        return httpMessage;

    }

    @ApiOperation(value="管理员修改用户", notes="这里使用id进行搜索修改，即主键，不使用有可能被修改的学号、身份证号")
    @PostMapping("/updateUser")
    public HttpMessage updateUser(@RequestParam(required = false) String name,
                                  @RequestParam(required = false) String number,
                                  @RequestParam(required = false) String idCard,
                                  @RequestParam(required = false) String password,
                                  @RequestParam(required = false) String email,
                                  @RequestParam Integer id){
        HttpMessage httpMessage = httpMessageObjectFactory.getObject();
        int result = 0;
        //密码加密
        if (password != null && !password.equals("")){
            password = DigestUtils.md5DigestAsHex(password.getBytes());
        }


        User user = userService.getIfUserById(id);
        //不存在该用户
        if(user == null){
            httpMessage.setCode(-1);
            httpMessage.setMessage("用户不存在，修改失败！");
            httpMessage.setResult(false);
            return httpMessage;
        }else {
            result = userService.updateUser(name, number, idCard, password, email, id);
        }
        //执行失败
        if(result == 0){
            httpMessage.setCode(-1);
            httpMessage.setMessage("系统异常，修改失败！");
            httpMessage.setResult(false);
        }else {
            httpMessage.setCode(200);
            httpMessage.setMessage("修改用户信息成功");
            httpMessage.setResult(true);
        }
        return httpMessage;
    }

    @ApiOperation(value="判断用户是否未绑定邮箱", notes="使用number进行判断")
    @GetMapping("/userIfBindEmail")
    public HttpMessage userIfBindEmail(@RequestParam String number){
        HttpMessage httpMessage = httpMessageObjectFactory.getObject();

        String result = userService.userIfBindEmail(number);
        log.info("用户绑定的邮箱"+result);
        //执行失败
        if(result == null || result.equals("")){
            httpMessage.setCode(-1);
            httpMessage.setMessage("未绑定邮箱！");
            httpMessage.setResult(false);
        }else {
            httpMessage.setCode(200);
            httpMessage.setMessage("已经绑定邮箱。");
            httpMessage.setResult(true);
        }
        return httpMessage;
    }

}
